const fs = require("fs"); // 添加fs模块导入
const path = require("path");

// 提取字符串中的所有数字并转换为整数
function extractNumbers(str) {
  const matches = str.match(/\d+/g) || [];
  return matches.map((numStr) => parseInt(numStr, 10));
}

// 修改函数签名，接收一个对象参数
function renameNumber({ newNameStart, newNameEnd, serialNumber, mode, dir }) {
  //校验目录是否存在
  if (!fs.existsSync(dir)) {
    return {
      msg: "目录不存在",
      data: [],
    };
  }

  let fileList = [];
  let newList = [];
  let currentSerialNumber = parseInt(serialNumber, 10);

  // 使用同步API读取目录
  const files = fs.readdirSync(dir);

  // 构建文件列表
  files.forEach((v) => {
    fileList.push({
      fullPath: path.join(dir, v), // 使用path.join确保路径正确性
      name: v,
      suffix: v.substring(v.lastIndexOf(".")), // 获取文件后缀
    });
  });

  // 排序文件列表
  fileList.sort((a, b) => {
    const numsA = extractNumbers(a.fullPath);
    const numsB = extractNumbers(b.fullPath);

    for (let i = 0; i < Math.min(numsA.length, numsB.length); i++) {
      if (numsA[i] !== numsB[i]) {
        return numsA[i] - numsB[i];
      }
    }

    return numsA.length - numsB.length;
  });

  // 重命名或生成新文件名列表
  fileList.forEach((v) => {
    const newName = path.join(
      dir,
      `${newNameStart}${currentSerialNumber}${newNameEnd}${v.suffix}`
    );
    currentSerialNumber++;

    newList.push({
      oldName: v.name,
      newName: path.basename(newName),
    });

    if (mode === "rename") {
      try {
        fs.renameSync(v.fullPath, newName);
      } catch (renameErr) {
        console.error(`重命名文件失败 ${v.fullPath}:`, renameErr);
      }
    }
  });
  return {
    msg: mode === "rename" ? "重命名成功" : "预览模式",
    data: newList,
  };
}
module.exports = renameNumber;
